package com.kit;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by 石头哥哥 on 9/6/16.
 * PACKAGE_NAME:  com.kit
 * COMMENT : 校验和
 */
public class CheckSum {

    /**
     * Read the file and calculate the SHA-1 checksum
     *
     * @param filename the file of name
     * @return the hex representation of the SHA-1 using uppercase chars
     * @throws FileNotFoundException    if the file does not exist, is a directory rather than a
     *                                  regular file, or for some other reason cannot be opened for
     *                                  reading
     * @throws IOException              if an I/O error occurs
     * @throws NoSuchAlgorithmException should never happen
     */
    private static String sha1sum(String filename) throws
            IOException, NoSuchAlgorithmException {
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
        try (InputStream input = new FileInputStream(new PathMatchingResourcePatternResolver()
                .getResource(filename).getURI().getPath())) {
            byte[] buffer = new byte[8192];
            int len = input.read(buffer);

            while (len != -1) {
                sha1.update(buffer, 0, len);
                len = input.read(buffer);
            }
            return DatatypeConverter.printHexBinary(sha1.digest()).toLowerCase();
        }
    }


    public static void main(String[] args) throws Exception {
        String path = new PathMatchingResourcePatternResolver()
                .getResource("netty.properties").getURI().getPath();

        String check_sum = sha1sum("netty.properties");



        Process process = Runtime.getRuntime().exec("sha1sum " + path);
        InputStream inputStream = process.getInputStream();
        byte[] data = new byte[40];
        inputStream.read(data,0,40);
        String check_sum_with_process = new String(data);
        if (check_sum_with_process.equals(check_sum)) {
            System.out.println(check_sum_with_process);
        }

    }
}
